package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.user.dto.ApAuthor;
import com.heima.user.dto.AuthDto;
import com.heima.user.dto.UserRealnameDto;
import com.heima.user.dto.WmUser;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserRealname;
import com.heima.user.feign.ArticleFeign;
import com.heima.user.feign.MediaFeign;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.IApUserRealnameService;
import com.heima.user.service.IApUserService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * APP实名认证信息表 服务实现类
 * </p>
 *
 * @author Wq
 * @since 2022-09-30
 */
@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements IApUserRealnameService {

    @Autowired
    private MediaFeign mediaFeign;
    @Autowired
    private ArticleFeign articleFeign;
    @Autowired
    private IApUserService apUserService;

    @Override
    public ResponseResult getListByPage(UserRealnameDto dto) {
        //1、参数校验
        Integer status = dto.getStatus();
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2、执行分页查询
        LambdaQueryWrapper<ApUserRealname> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(!ObjectUtils.isEmpty(status), ApUserRealname::getStatus, status);
        Page<ApUserRealname> page = this.page(new Page<>(dto.getPage(), dto.getSize()), wrapper);
        //封装返回
        return new PageResponseResult(
                dto.getPage(),
                dto.getSize(),
                page.getTotal(),
                page.getRecords());
    }

    @Override
    @GlobalTransactional  //加入分布式事务
    public ResponseResult auth(AuthDto dto, int flag) {
        //flag 1 表示通过  0表示失败
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 根据id查询实名认证的信息
        Integer userId = dto.getId();
        LambdaQueryWrapper<ApUserRealname> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(userId != null, ApUserRealname::getUserId, userId);
        ApUserRealname apUserRealname = this.getOne(wrapper);

        if (flag == 0) {
            //标记是1  失败
            apUserRealname.setStatus(2);
            apUserRealname.setReason(dto.getMsg());
            this.updateById(apUserRealname);
        } else if (flag == 1) {
            //成功
            //通过userId查询用户详细信息
            ApUser apUser = apUserService.getById(userId);
            //1、在自媒体微服务 创建自媒体账户 成为自媒体人
            WmUser wmUser = createWmUser(apUser);
            //2、在文章微服务  创建作者  成为文章作者
            ApAuthor apAuthor = createApArticle(apUser, wmUser.getId());
            //3、更新自媒体表中 apAuthor_id
            wmUser.setApAuthorId(apAuthor.getId());
            mediaFeign.updateUser(wmUser);
            //4、修改apUserRealname状态
            apUserRealname.setStatus(9); //状态 0 创建中 1 待审核  2 审核失败  9 审核通过
            apUserRealname.setReason(dto.getMsg());
            this.updateById(apUserRealname);
            //5、修改ap_user的状态
            apUser.setFlag(1);
            apUser.setIsIdentityAuthentication(true);
            apUserService.updateById(apUser);
        }
        return ResponseResult.okResult();
    }

    /**
     * 创建文章作者
     *
     * @param apUser   app用户
     * @param wmUserId 自媒体用户id
     * @return {@code ApAuthor}
     */
    private ApAuthor createApArticle(ApUser apUser, Integer wmUserId) {
        ApAuthor apAuthor = new ApAuthor();
        // apAuthor.setId();
        apAuthor.setName(apUser.getName());
        apAuthor.setType(2);
        apAuthor.setUserId(apUser.getId());
        apAuthor.setWmUserId(wmUserId);
        ResponseResult<ApAuthor> apAuthorResponseResult = articleFeign.saveAuthor(apAuthor);
        if (apAuthorResponseResult.getCode() == 0) {
            return apAuthorResponseResult.getData();
        } else {
            throw new RuntimeException("远程调用失败");
        }
    }

    /**
     * 创建自媒体用户
     *
     * @param apUser app用户
     * @return {@code WmUser}
     */
    private WmUser createWmUser(ApUser apUser) {
        WmUser wmUser = new WmUser();
        // wmUser.setId(apUser.getId());  主键自增
        wmUser.setApUserId(apUser.getId());
        // wmUser.setApAuthorId();  文章作者id  等创建文章作者后在赋值
        wmUser.setName(apUser.getName());
        wmUser.setPassword(apUser.getPassword());
        wmUser.setSalt(apUser.getSalt());
        // wmUser.setNickname();
        wmUser.setImage(apUser.getImage());
        // wmUser.setLocation();
        wmUser.setPhone(apUser.getPhone());
        wmUser.setStatus(9);
        // wmUser.setEmail();
        wmUser.setType(0);
        wmUser.setScore(0);
        // wmUser.setLoginTime();
        wmUser.setCreatedTime(apUser.getCreatedTime());
        ResponseResult<WmUser> wmUserResponseResult = mediaFeign.saveUser(wmUser);
        if (wmUserResponseResult.getCode() == 0) {
            return wmUserResponseResult.getData();
        } else {
            throw new RuntimeException("远程调用失败");
        }
    }
}
